package com.zer0.tga.level;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import com.zer0.tga.math.RandNum;
import com.zer0.tga.tile.Tile;
import com.zer0.tga.tile.WallTile;


public class RoomGenerator {
	
	private static ArrayList<int[]> roomList;

	public RoomGenerator()
	{
		roomList = new ArrayList<int[]>();
		importFromFile();
	}
	
	public static void importFromFile(){
		
		File roomFile = new File("res/rooms2.txt");
		BufferedReader reader = null;
		try {
			 reader = new BufferedReader(new FileReader(roomFile));
			
		
		String line = null;	
	    while ((line=reader.readLine()) != null) 
	    {
	    	if(line.length() == (Room.ROOM_X * Room.ROOM_Y))
	    	{
	    		int[] newRoomTemp = new int[Room.ROOM_X * Room.ROOM_Y];
	    		for(int i=0;i<line.length()-1;i++)
	    		{
	    			newRoomTemp[i] = Integer.parseInt(line.substring(i, i+1));
	    		}
	    		//add the last one
	    		newRoomTemp[line.length()-1] = Integer.parseInt(line.substring(line.length()-1));
	    		
	    		//add to the list
	    		roomList.add(newRoomTemp);
	    	}
	    }
	    reader.close();
	
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
	}
	
	public Tile[] generate(Level level)
	{
		int[] room = roomList.get(RandNum.getRandNum(0, roomList.size()));
		
		Tile ret[] = new Tile[Room.ROOM_X * Room.ROOM_Y];
		
		for(int i=0;i<room.length;i++)
		{
			if (room[i] == 0)
			{
				ret[i] = new WallTile();
				ret[i].setSide(0);
			}
			else if(room[i] == 1)
			{
				ret[i] = new WallTile();
				ret[i].setSide(1);
				
			}
			else if(room[i] == 2)
			{
				ret[i] = new WallTile();
				ret[i].setSide(2);
			}
			else if(room[i] == 3)
			{
				ret[i] = new WallTile();
				ret[i].setSide(3);
			}
			else if(room[i] == 4)
			{
				ret[i] = new Tile();
			}
			ret[i].init(level, (i%Room.ROOM_X), (i/Room.ROOM_X));
		
		}
		
		return ret;
	}
	
	
}
